﻿// Apache-2.0 License
// Copyright (c) 2021-2022 朱飞龙
// 电话/微信：18706708563  QQ群：136192142

using Admin.NET.Application.Util.Extension;
using Admin.NET.Interface.Kingdee.Util.Extension;
using Radius.NET.Interface.Kingdee.Entity;

namespace Radius.NET.Interface.Kingdee.Service.BasicInfoModule;


/// <summary>
/// 基础资料服务
/// </summary>
[ApiDescriptionSettings(KingdeeConfigConst.GroupName, Order = 002)]
public class MisVendorService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<MisVendor> misVendorRespository;
    private readonly KingdeeUtil _kingdeeUtil;

    /// <summary>
    /// 
    /// </summary>
    /// <param name="_misVendorRespository"></param>
    /// <param name="kingdeeUtil"></param>
    public MisVendorService(SqlSugarRepository<MisVendor> _misVendorRespository,
        KingdeeUtil kingdeeUtil)
    {
        _kingdeeUtil = kingdeeUtil;
        misVendorRespository = _misVendorRespository;
    }

    #region 同步金蝶云星空供应商档案到本地
    /// <summary>
    /// 同步金蝶云星空供应商档案到本地
    /// </summary>
    /// <returns></returns>
    [HttpPost("/kindeeIcloud/basicinfo/misvendorlist/{cid}"), AllowAnonymous]
    public async Task<object> SyncMisVendorList(int cid, string BDate)
    {
        var KingdeeUtil = await _kingdeeUtil.GetClient("kindeeIcloud_basicinfo_misvendorlist");
        List<MisVendor> InserLsit = new();
        List<MisVendor> UpdateList = new();

        if (string.IsNullOrEmpty(BDate))
        {
            BDate = DateTime.Now.ToString("yyyy-MM-dd");
        }

        string filekeys = $"FUseOrgId.FNumber = '{KingdeeConfigConst.ORGID}' and FCreateDate >='{BDate}'";

        //获取云星空BOM清单
        var list = KingdeeUtil.Query<BD_Supplier_Dto>("BD_Supplier", filekeys);

        if (list.Count == 0)
        {
            return await Task.FromResult(Oops.Oh("金蝶无数据可同步！"));
        }
        //循环供应商档案插入本地表
        foreach (var item in list)
        {
            MisVendor obj = new()
            {
                ContactNum = item.FNumber,
                ContactName = item.FName,
                Status = item.FForbidStatus == "A" ? "有效" : "冻结",
                Phone = item.FLocNewContactFNumber,
                Address = item.FLocAddress,
                CurrencyType = item.FPayCurrencyIdFNumber,
                PayMent = item.FSettleTypeIdFNumber,
                TaxType = item.FInvoiceType,
                CreateDate = item.FCreateDate,
                _cid = cid,
            };
            //判断供应商档案是否存在
            if (!await misVendorRespository.IsAnyAsync(x => x.ContactNum == item.FNumber))
            {
                InserLsit.Add(obj);
            }
            else
            {
                UpdateList.Add(obj);
            }
        }
        if (InserLsit.Count == 0 && UpdateList.Count == 0)
        {
            throw Oops.Oh("当前同步的供应商本系统中已存在！");
        }

        try
        {
            //misVendorRespository.Context.Ado.BeginTran();
            var obj = await misVendorRespository.AsInsertable(InserLsit).ExecuteCommandAsync();
            obj = await misVendorRespository.AsUpdateable(UpdateList)
                .UpdateColumns(x => new
                {
                    x.ContactName,
                    x.Status,
                    x.ContactPerson,
                    x.Phone,
                    x.VendorTypeID,
                    x.Address,
                    x.CurrencyType,
                    x.PayMent,
                    x.TaxType
                }).ExecuteCommandAsync();
            //misVendorRespository.Context.Ado.CommitTran();
            return InserLsit.Concat(UpdateList);
        }
        catch (Exception ex)
        {
            //misVendorRespository.Context.Ado.RollbackTran();
            throw Oops.Oh(ex.Message);
        }
    }
    #endregion
}
